package com.vitetest.api.controller;

import com.vitetest.api.dto.ApiResponse;
import com.vitetest.api.dto.ProductRequest;
import com.vitetest.api.dto.ProductResponse;
import com.vitetest.api.service.ProductService;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

@RestController
@RequestMapping("/api/products")
@CrossOrigin(origins = "*")
public class ProductController {
    
    @Autowired
    private ProductService productService;
    
    /**
     * 添加新商品
     * POST /api/products
     */
    @PostMapping
    public ResponseEntity<ApiResponse<ProductResponse>> addProduct(@Valid @RequestBody ProductRequest request) {
        try {
            ProductResponse product = productService.addProduct(request);
            return ResponseEntity.ok(new ApiResponse<ProductResponse>(true, "商品添加成功", product, System.currentTimeMillis()));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(new ApiResponse<ProductResponse>(false, "商品添加失败：" + e.getMessage(), null, System.currentTimeMillis()));
        }
    }
    
    /**
     * 根据ID获取商品
     * GET /api/products/{id}
     */
    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<ProductResponse>> getProductById(@PathVariable Long id) {
        try {
            ProductResponse product = productService.getProductById(id);
            return ResponseEntity.ok(new ApiResponse<ProductResponse>(true, "获取商品成功", product, System.currentTimeMillis()));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(new ApiResponse<ProductResponse>(false, "获取商品失败：" + e.getMessage(), null, System.currentTimeMillis()));
        }
    }
    
    /**
     * 获取所有激活的商品
     * GET /api/products
     */
    @GetMapping
    public ResponseEntity<ApiResponse<List<ProductResponse>>> getAllActiveProducts() {
        try {
            List<ProductResponse> products = productService.getAllActiveProducts();
            return ResponseEntity.ok(new ApiResponse<List<ProductResponse>>(true, "获取商品列表成功", products, System.currentTimeMillis()));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<List<ProductResponse>>(false, "获取商品列表失败：" + e.getMessage(), null, System.currentTimeMillis()));
        }
    }
    
    /**
     * 分页获取激活的商品
     * GET /api/products/page?page=0&size=10
     */
    @GetMapping("/page")
    public ResponseEntity<ApiResponse<Page<ProductResponse>>> getActiveProductsPage(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            Page<ProductResponse> products = productService.getActiveProductsPage(page, size);
            return ResponseEntity.ok(new ApiResponse<Page<ProductResponse>>(true, "获取商品分页成功", products, System.currentTimeMillis()));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<Page<ProductResponse>>(false, "获取商品分页失败：" + e.getMessage(), null, System.currentTimeMillis()));
        }
    }
    
    /**
     * 根据分类获取商品
     * GET /api/products/category/{category}
     */
    @GetMapping("/category/{category}")
    public ResponseEntity<ApiResponse<List<ProductResponse>>> getProductsByCategory(@PathVariable String category) {
        try {
            List<ProductResponse> products = productService.getProductsByCategory(category);
            return ResponseEntity.ok(new ApiResponse<List<ProductResponse>>(true, "获取分类商品成功", products, System.currentTimeMillis()));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<List<ProductResponse>>(false, "获取分类商品失败：" + e.getMessage(), null, System.currentTimeMillis()));
        }
    }
    
    /**
     * 根据名称搜索商品
     * GET /api/products/search?name=商品名称
     */
    @GetMapping("/search")
    public ResponseEntity<ApiResponse<List<ProductResponse>>> searchProductsByName(@RequestParam String name) {
        try {
            List<ProductResponse> products = productService.searchProductsByName(name);
            return ResponseEntity.ok(new ApiResponse<List<ProductResponse>>(true, "搜索商品成功", products, System.currentTimeMillis()));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<List<ProductResponse>>(false, "搜索商品失败：" + e.getMessage(), null, System.currentTimeMillis()));
        }
    }
    
    /**
     * 根据价格范围搜索商品
     * GET /api/products/search/price?minPrice=10&maxPrice=100
     */
    @GetMapping("/search/price")
    public ResponseEntity<ApiResponse<List<ProductResponse>>> searchProductsByPriceRange(
            @RequestParam BigDecimal minPrice,
            @RequestParam BigDecimal maxPrice) {
        try {
            List<ProductResponse> products = productService.searchProductsByPriceRange(minPrice, maxPrice);
            return ResponseEntity.ok(new ApiResponse<List<ProductResponse>>(true, "按价格范围搜索商品成功", products, System.currentTimeMillis()));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<List<ProductResponse>>(false, "按价格范围搜索商品失败：" + e.getMessage(), null, System.currentTimeMillis()));
        }
    }
    
    /**
     * 更新商品信息
     * PUT /api/products/{id}
     */
    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse<ProductResponse>> updateProduct(
            @PathVariable Long id,
            @Valid @RequestBody ProductRequest request) {
        try {
            ProductResponse product = productService.updateProduct(id, request);
            return ResponseEntity.ok(new ApiResponse<ProductResponse>(true, "商品更新成功", product, System.currentTimeMillis()));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(new ApiResponse<ProductResponse>(false, "商品更新失败：" + e.getMessage(), null, System.currentTimeMillis()));
        }
    }
    
    /**
     * 删除商品（软删除）
     * DELETE /api/products/{id}
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<Void>> deleteProduct(@PathVariable Long id) {
        try {
            productService.deleteProduct(id);
            return ResponseEntity.ok(new ApiResponse<Void>(true, "商品删除成功", null, System.currentTimeMillis()));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(new ApiResponse<Void>(false, "商品删除失败：" + e.getMessage(), null, System.currentTimeMillis()));
        }
    }
    
    /**
     * 更新商品库存
     * PATCH /api/products/{id}/stock
     */
    @PatchMapping("/{id}/stock")
    public ResponseEntity<ApiResponse<ProductResponse>> updateProductStock(
            @PathVariable Long id,
            @RequestParam Integer stock) {
        try {
            ProductResponse product = productService.updateProductStock(id, stock);
            return ResponseEntity.ok(new ApiResponse<ProductResponse>(true, "库存更新成功", product, System.currentTimeMillis()));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(new ApiResponse<ProductResponse>(false, "库存更新失败：" + e.getMessage(), null, System.currentTimeMillis()));
        }
    }
    
    /**
     * 获取库存不足的商品
     * GET /api/products/low-stock?threshold=10
     */
    @GetMapping("/low-stock")
    public ResponseEntity<ApiResponse<List<ProductResponse>>> getLowStockProducts(
            @RequestParam(defaultValue = "10") Integer threshold) {
        try {
            List<ProductResponse> products = productService.getLowStockProducts(threshold);
            return ResponseEntity.ok(new ApiResponse<List<ProductResponse>>(true, "获取库存不足商品成功", products, System.currentTimeMillis()));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<List<ProductResponse>>(false, "获取库存不足商品失败：" + e.getMessage(), null, System.currentTimeMillis()));
        }
    }
    
    /**
     * 获取所有商品分类
     * GET /api/products/categories
     */
    @GetMapping("/categories")
    public ResponseEntity<ApiResponse<List<String>>> getAllCategories() {
        try {
            List<String> categories = productService.getAllCategories();
            return ResponseEntity.ok(new ApiResponse<List<String>>(true, "获取商品分类成功", categories, System.currentTimeMillis()));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<List<String>>(false, "获取商品分类失败：" + e.getMessage(), null, System.currentTimeMillis()));
        }
    }
    
    /**
     * 获取分类统计信息
     * GET /api/products/categories/stats
     */
    @GetMapping("/categories/stats")
    public ResponseEntity<ApiResponse<List<Object[]>>> getCategoryStatistics() {
        try {
            List<Object[]> stats = productService.getCategoryStatistics();
            return ResponseEntity.ok(new ApiResponse<List<Object[]>>(true, "获取分类统计成功", stats, System.currentTimeMillis()));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<List<Object[]>>(false, "获取分类统计失败：" + e.getMessage(), null, System.currentTimeMillis()));
        }
    }
} 